/**
 * 聚合管道分页
 */
module.exports = async ({
	// prettier-ignore
	req,
	model,
	filterPipe = {},
	sortPipe = {},
	lookupPipe = [],
	findAfterCallback = () => {},
}) => {
	// 获取筛选条件, 分页参数不进入条件.
	const filter = req.query;
	const { page = 1, size = 10, paging_all = false } = filter;
	delete filter.page;
	delete filter.size;
	delete filter.paging_all;

	let outRes = await model
		.aggregate([
			// 匹配条件
			{
				$match: filterPipe,
			},
			// 文档数量添加到最外层
			{
				$facet: {
					total: [{ $count: "total" }],
					data: [
						// 排序
						{
							$sort: sortPipe,
						},
						// 分页
						{ $skip: paging_all ? 0 : (Number(page) - 1) * Number(size) },
						{ $limit: paging_all ? Number.MAX_SAFE_INTEGER : Number(size) },
						// 联表查询
						...lookupPipe,
					],
				},
			},
		])
		.exec();
	outRes = { total: outRes[0].total[0]?.total || 0, data: outRes[0].data };

	findAfterCallback(outRes);
	return outRes;
};
